package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class ShowParamsServlet
 */
@WebServlet("/ShowParamsServlet")
public class ShowParamsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowParamsServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String title = "Reading All Request Parameters";
		out.println(Constants.docType + 
				"<html><head><title>" + title + "</title></head>" +
				"<body><h1>" + title + "</h1><table border=\"1\" align=\"center\">" +
				"<tr><th>Parameter Name</th><th>Parameter Value(s)</th></tr>" 
				);
		Enumeration<String> paramNames = request.getParameterNames();
		while(paramNames.hasMoreElements()){
			String paramName = paramNames.nextElement();
			out.println("<tr><td>" + paramName + "</td><td>");
			String[] paramValues = request.getParameterValues(paramName);
			if(1 == paramValues.length){
				String paramValue = paramValues[0];
				if(0 == paramValues.length){
					out.println("<em>NO VALUE</em>");
				}else{
					out.println(paramValue);
				}
			}else{
				out.println("<ul>");
				for(String paramValue : paramValues){
					out.println("<li>" + paramValue + "</li>");
				}
				out.println("</ul>");
			}
			out.println("</td></tr>");
		}
		
		//
		out.println("</table><body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private static final Logger logger = 
			Logger.getLogger(ShowParamsServlet.class);

}
